/*
 * Copyright (c) 2019 Author: Fancyears Milos Malvis @1243093366@qq.com
 * ALL COPYRIGHT REVERSED.
 */

package com.fancyears.encrypt;

import com.fancyears.util.EncryptCodeUtils;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: Fancyears Milos Malvis
 * @Date: Created in  2019/6/19 17:07
 * @Modified By:
 */
public class Se {
    /**
     * 偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量，这个偏移量估计要固定死，或者需要动态生成
     */
    private static String iv = "0123456789ABCDEF";
    /**
     * 加密算法
     */
    private static String Algorithm = "AES";
    /**
     * 算法/模式/补码方式
     */
    private static String AlgorithmProvider = "AES/CBC/PKCS5Padding";

    public static byte[] generatorKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(Algorithm);
        keyGenerator.init(256);//默认128，获得无政策权限后可为192或256
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    public static IvParameterSpec getIv(String iv) throws UnsupportedEncodingException {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
        System.out.println("偏移量：" + byteToHexString(ivParameterSpec.getIV()));
        return ivParameterSpec;
    }

    /**
     * 加密字符串
     * @param src 原始字符串
     * @param key 密钥
     * @param iv
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     */
    public static byte[] encrypt(String src, byte[] key,String iv) throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
        SecretKey secretKey = new SecretKeySpec(key, Algorithm);
        IvParameterSpec ivParameterSpec = getIv(iv);
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
        return cipherBytes;
    }

    /**
     * 解密
     * @param src 被加密后的字符串
     * @param key 密钥
     * @param iv 偏移量
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(String src, byte[] key,String iv) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, Algorithm);

        IvParameterSpec ivParameterSpec = getIv(iv);
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] hexBytes = hexStringToBytes(src);
        byte[] plainBytes = cipher.doFinal(hexBytes);
        return plainBytes;
    }

    /**
     * 将byte转换为16进制字符串
     *
     * @param src
     * @return
     */
    public static String byteToHexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append("0");
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    /**
     * 将16进制字符串装换为byte数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return b;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static void main(String[] args) {
        try {
            /**
             * 产生随机偏移
             */
            String iv=EncryptCodeUtils.getRandomChar(16);
            System.out.println("偏移量:"+iv);//偏移量可以考虑放在redis中，每次只要登录操作或者验证失败后都会重新生成一次偏移量
            byte key[] = generatorKey();
            // 密钥必须是16的倍数
//            byte key[] = iv.getBytes("utf-8");//hexStringToBytes("0123456789ABCDEF");

//            dec();

//            偏移量:LaWPVlOQkOlvrrxr
//            密钥:4c615750566c4f516b4f6c7672727872
//            原字符串:jack
//            偏移量：4c615750566c4f516b4f6c7672727872
//            加密：622eb7ca29744ab5f4aae36da43ee381
//            偏移量：4c615750566c4f516b4f6c7672727872
//            解密：jack

            String src = "jack";//原字符串
            System.out.println("密钥:" + byteToHexString(key));
            System.out.println("原字符串:" + src);
            String enc = byteToHexString(encrypt(src, key,iv));//加密后的字符串
            System.out.println("加密：" + enc);
            System.out.println("解密：" + new String(decrypt(enc, key,iv), "utf-8"));

        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void dec() throws Exception {
        byte [] x;//秘钥
        x=hexStringToBytes("6ae49ad95f1623c141decd6945c79b6036ef85c22cd93a7d7a3705babae9c9b9");
        System.out.println(x);
//        667a5558664e67644c7957786175544d
        System.out.println("解密：" + new String(decrypt("f74f1582dbfbe0403a31000b5132310c", x,"ARKyiNvGXJfv13oJ"), "utf-8"));
    }

    private static byte[] getBytesFromString(String src) {
       if(StringUtils.isEmpty(src)){
           throw new StringIndexOutOfBoundsException("秘钥不能没空");
       }
       byte[] result=new byte[src.length()];
        for (int i = 0; i < src.length(); i++) {
            result[i]= (byte) src.charAt(i);
        }
        return result;
    }
}